package com.zyl.blog.tasks.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 任务调度器配置
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.tasks.config
 * @ClassName: TaskSchedulerConfig
 * @Author FinalFantasy
 * @Date 2025/8/12-10:30
 */
@Configuration
public class TaskSchedulerConfig {

    /**
     * 配置任务调度器，使用JDK24虚拟线程
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        /* 设置线程名称前缀 */
        scheduler.setThreadNamePrefix("task-scheduler-");
        /* 使用虚拟线程工厂 */
        scheduler.setThreadFactory(Thread.ofVirtual().factory());
        /* 根据CPU核心数调整（建议核心数*2） */
        scheduler.setPoolSize(5);
        /* 新增：任务拒绝策略（当任务过多时缓冲，而非直接拒绝） */
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        /* 初始化 */
        scheduler.initialize();
        return scheduler;
    }
}
